撰寫 React 專案時,我們時常會為了傳遞全域狀態內容,使用 <Provider>
包裹 入口 <App />
的寫法。
今天來練習一下,測試 <Provider>
傳入的內容是否符合預期的寫法。
<ThemeProvider>
傳遞深淺色主題。<ThemeProvider>
有成功傳遞 深色主題 至 專案。<ThemeProvider>
預設為淺色主題。
/src/provider/provider.tsx
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
const darkTheme = createTheme({
palette: {
mode: 'dark',
},
});
function AppProvider({children}: {children: React.ReactNode}) {
return (
<ThemeProvider theme={darkTheme}>
<CssBaseline />
{children}
</ThemeProvider>
);
}
export default AppProvider;
/src/app.tsx
import './App.css';
import Counter from './components/counter/counter';
import AppProvider from './providers/providers';
function App() {
return (
<AppProvider>
<div className="App">
<ThemeMode />
</div>
</AppProvider>
);
}
export default App;
/src/components/themeMode/themeMode.tsx
import { Typography, useTheme } from "@mui/material";
export default function ThemeMode(){
const theme = useTheme();
return(
<Typography component={"h1"}>{theme.palette.mode} mode</Typography>
)
}
撰寫測試: 預期為深色主題。
import { render, screen } from "@testing-library/react";
import ThemeMode from "./mode";
describe("ThemeProvider", () => {
test("Render dark mode correctly!", () => {
render(<ThemeMode />);
const modeEl = screen.getByRole("heading", {
level: 1
});
expect(modeEl).toHaveTextContent("dark mode");
});
});
測試結果:
FAIL src/components/mode/mode.test.tsx
● ThemeProvider › Render dark mode correctly!expect(element).toHaveTextContent() Expected element to have text content: dark mode Received: light mode
這裡失敗的原因是:ThemeMode 的測試內容沒有接收到
<ThemeProvider />
傳入的主題設定。
修改測試: 在 render(元件, 其他設定) 加入 {wrapper: ThemeProvider}
。
import { render, screen } from "@testing-library/react";
import ThemeMode from "./mode";
import AppProvider from "../../providers/providers";
describe("ThemeProvider", () => {
test("Render dark mode correctly!", () => {
render(<ThemeMode />, {
wrapper: AppProvider
});
const modeEl = screen.getByRole("heading", {
level: 1
});
expect(modeEl).toHaveTextContent("dark mode");
});
});
測試結果:
PASS src/components/themeMode/themeMode.test.tsx